/**
 *  JSimProd - Java simulation code for production processes
 *  Copyleft Jorge Mira Yagüe <jorge.mira.yague@gmail.com>
 *  Universidad de Alicante 2009
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package lib.model.queue;

import lib.plan.Item;

/**
 * The Priority Last In First Out (PLIFO) queue is a kind of queue where items
 * are added to the queue with a prority order, being 1 the highest priority, 2
 * the second priority and so on.
 * In case there are two or more items with the same priority, the queue will
 * add them with a LIFO order.
 * @see LIFOQueue
 * @see Queue
 * @see Item
 * @author Jorge Mira Yagüe
 */
public class PLIFOQueue extends Queue {

    /**
     * Builds a priority LIFO queue
     */
    public PLIFOQueue() {
        super(QueueType.PLIFO);
    }

    /**
     * Adds the item to the queue with a LIFO order
     * @param item the item to be added to the queue
     */
    @Override
    public void add(Item item) {
        int index = indexOf(item.getPriority());
        if (index == size) {
            elements.add(item);
        } else {
            elements.add(index, item);
        }
        size++;
    }

    private int indexOf(int n) {
        if (size == 0) {
            return 0;
        }
        int start = 0;
        int end = size - 1;
        int middle = 0;
        while (start <= end) {
            middle = (end + start) / 2;
            if (n > elements.get(middle).getPriority()) {
                start = middle + 1;
            } else {
                end = middle - 1;
            }
        }
        return start;
    }
}
